﻿using System.Reflection;
using System.Web;
using System.Web.Mvc;

namespace WebShop.Infrastructure
{

    public class ImageBinderAttribute : CustomModelBinderAttribute
    {
        public string FieldName { get; set; }
        public override IModelBinder GetBinder()
        {
            return new ImageModelBinder(FieldName);
        }
    }

    public class ImageModelBinder : DefaultModelBinder
    {
        private readonly string _fieldName;
        public ImageModelBinder(string fieldName)
        {
            _fieldName = fieldName;
        }

        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            try
            {
                var obj = base.BindModel(controllerContext, bindingContext);

                ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "." + _fieldName);
                if (valueResult == null)
                {
                    valueResult = bindingContext.ValueProvider.GetValue(_fieldName);
                }
                if (valueResult != null)
                {
                    HttpPostedFileBase file = (HttpPostedFileBase)valueResult.ConvertTo(typeof(HttpPostedFileBase));
                    if (file != null)
                    {
                        byte[] tempImage = new byte[file.ContentLength];
                        file.InputStream.Read(tempImage, 0, file.ContentLength);
                        PropertyInfo imagePoperty = bindingContext.ModelType.GetProperty(_fieldName);
                        imagePoperty.SetValue(obj, tempImage, null);
                    }
                }

                return obj;
            }
            catch
            {
                return null;
            }
        }
    }
}